//
//  JYNetworkTools.m
//  FpdCarInCube
//
//  Created by WXC on 2017/4/10.
//  Copyright © 2017年 jiaoyin. All rights reserved.
//

#import "JYNetworkTools.h"



@implementation JYNetworkTools

+ (void)requestWithEntity:(JYBaseEntity *)entity needHud:(BOOL)isNeedHud needDismiss:(BOOL)isNeedDismiss success:(void(^)(id responseObject))success failed:(void(^)(NSError *error))failure
{
    // 判断网络
    BOOL isNetAvailable = [self isConnectionAvailable];
    if (!isNetAvailable) {
        [ShowInfoView showMessage:@"网络异常，请检查网络连接"];
        failure(nil);
        return;
    }
    // 请求方法
    HttpRequestMethod reqMthod = [self getRequestMethod:entity.reqType];
    // 数据打包
    NSDictionary *params = [entity package:entity.reqType];
    // 请求url
    NSString *url = [JYURLManager URLOfEntity:entity];
    

    //1.获得请求管理者
    AFHTTPSessionManager *mgr = nil;
    if (entity.mgr) {
        mgr = entity.mgr;
        [mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    }
    else
    {
        mgr = [AFHTTPSessionManager manager];
    }
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [securityPolicy setValidatesDomainName:NO];
    securityPolicy.allowInvalidCertificates = YES; //还是必须设成YES
    mgr.securityPolicy = securityPolicy;
    
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    ((AFJSONResponseSerializer *)mgr.responseSerializer).removesKeysWithNullValues = YES;
   
    if (isNeedHud) {
        [SVProgressHUD showWithStatus:@"加载中..."];
    }
    
    
    switch (reqMthod) {
        case JYGet:
        {
            [mgr GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                // 处理返回结果
                [self dealSuccess:success andResponseObject:responseObject andEntity:entity needDismiss:isNeedDismiss];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failure) {
                    failure(error);
                    // 处理报错
                    [self dealError:error];
                }
            }];
        }
            break;
            
        case JYPost:
        {
            [mgr POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                // 处理返回结果
                [self dealSuccess:success andResponseObject:responseObject andEntity:entity needDismiss:isNeedDismiss];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (failure) {
                    failure(error);
                    // 处理报错
                    [self dealError:error];
                }
            }];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 处理返回结果
+ (void)dealSuccess:(void(^)(id responseObject))success andResponseObject:(id)responseObject andEntity:(JYBaseEntity *)entity needDismiss:(BOOL)isNeedDismiss
{
    JYLog(@"返回结果：%@",responseObject);
    if (isNeedDismiss) {
        [SVProgressHUD dismiss];
    }
    
    if (success) {
        NSNumber *state = responseObject[@"code"];
        if (state.integerValue == 0) {
            if (!isEmptyObject(responseObject[@"Data"])) {
                success(responseObject[@"Data"]);
                switch (entity.reqType) {
                    case FileUploadImgListUpload:
                    {
                        [SVProgressHUD showSuccessWithStatus:responseObject[@"Message"]];
                    }
                        break;
                        
                    
                        
                    default:
                    {
                        
                    }
                        break;
                }
            }
            else
            {
                
                switch (entity.reqType) {
                    case ProcessAlarmBySelfPost:
                    case InstallDeviceByIMEIPost:
                    case ModifyUserPasswordPost:
                    case UpdateNotifySettingPost:
                    case GetVehicleStatusPost:
                    case GetDatesOfDrivingPost:
                    case BillFocusEvents:
                    case GetVehicleCertificateByIdApp:
                    {
                        success(responseObject[@"Data"]);
                    }
                        break;
                        
                    case GetDriverIsExistByCardApp:
                    case GetLicenseIsExistByCardApp:
                    case GetIsExistsDrivingLicenseApp:
                    case AddIdentityCardApp:
                    case AddDrivingLicenseApp:
                    case AddDriversLicenseApp:
                    case AccountLogout:
                    case IsAllowInspect:
                    case InspectVehicle:
                    case Signature:
                    case AddIdeaFeedBackApp:
                    case ModifyPassword:
                    case ModifyBill:
                    case PayBill:
                    case AutoPayZeroBill:
                    case ForceUpdatePassword:
                    case AuditSchemeInstance:
                    case PayReceivable:
                    case PayPayable:
                    {
                        success(responseObject);
                    }
                        break;
                        
                    default:
                    {
                        //                        [SVProgressHUD showErrorWithStatus:@"服务器返回数据为空！"];
                        if ([responseObject[@"Data"] isKindOfClass:[NSArray class]]) {
                            success(responseObject[@"Data"]);
                        }
                        [SVProgressHUD dismiss];
                    }
                        break;
                }
            }
        }
        else if ([state.description isEqualToString:@"403"]) {
            [SVProgressHUD dismiss];
            [ShowInfoView showMessage:@"没有权限访问"];
        }else
        {
            [ShowInfoView showMessage:responseObject[@"Message"]];
        }
    }
    
}

#pragma mark - 处理报错
+ (void)dealError:(NSError *)error
{
    NSHTTPURLResponse *head = error.userInfo[@"com.alamofire.serialization.response.error.response"];
    JYLog(@"%@",head.allHeaderFields);
    JYLog(@"%zi",head.statusCode);
    NSData *data = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
    if (data) {
        [SVProgressHUD dismiss];
        NSDictionary *body = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([body isKindOfClass:[NSDictionary class]]) {
            NSNumber *State = [body safeObjectForKey:@"State"];
            NSInteger state = [State integerValue];
            if (state == 10) {
//                [JYUtils logOut];
            }
            else if (state == 11 || state == 12) {
                [ShowInfoView showMessage:[body safeObjectForKey:@"Message"]];
//                [JYUtils logOut];
            }
            else
            {
                if (head.statusCode == 500) {
                    [ShowInfoView showMessage:@"网络错误，请稍后重试..."];
                }
                else
                {
                    [ShowInfoView showMessage:[NSString stringWithFormat:@"%@",[body safeObjectForKey:@"Message"]]];
                }
                
            }
        }else{
            
            if (head.statusCode == 500) {
                [ShowInfoView showMessage:@"网络错误，请稍后重试..."];
            }
        }
    }
    
}

#pragma mark - 判断请求方法
+ (HttpRequestMethod)getRequestMethod:(RequestType)type
{
    HttpRequestMethod reqMthod;
    switch (type) {
        case LoginReqPost:
        case GetContractsListApp:
        case GetContractsDetailByIdApp:
        case GetContractExtraChargesByIdApp:
        case GetStockInOutsOfContractByIdApp:
        case GetReceivablesOfContractByIdApp:
        case GetVehicleListApp:
        case GetVehicleDetailByIdApp:
        case GetVehicleCertificateByIdApp:
        case GetVehiclePlateByIdApp:
        case GetVehicleContractsByIdApp:
        case GetIntendedOrdersListApp:
        case VehicleLineList:
        case VehicleModelList:
        case SysBasicDictionaryList:
        case SysBasicGetCompanyTree:
        case GetUserInfoApp:
        case GetIntendedOrdersDetailByIdApp:
        case GetIntendedExpensesListByIdApp:
        case GetTrafficViolationListApp:
        case GetDriverListOrDetailApp:
        case GetDriverLicenseListApp:
        case GetDriverContractsListApp:
        case StockInOutListApp:
        case FileUploadImgListUpload:
        case GetDriverIsExistByCardApp:
        case AddIdentityCardApp:
        case AddDrivingLicenseApp:
        case AddDriversLicenseApp:
        case InspectVehicle:
        case Signature:
        case GetInsuranceListApp:
        case GetPageAccidentListApp:
        case GetSingleAccidentApp:
        case GetFinanceResultListApp:
        case GetReceivablePaidRecordsApp:
        case AddIdeaFeedBackApp:
        case ModifyPassword:
        case ProductTypeSelectList:
        case GetMyApprovalListApp:
        case GetApprovalDetailApp:
        case AuditSchemeInstance:
        case UnreceivedBills:
        case UnpaidBills:
        case ModifyBill:
        case PayBill:
        case BillHistory:
        case GetLicenseIsExistByCardApp:
        case GetIsExistsDrivingLicenseApp:
        case AutoPayZeroBill:
        case CompletedBills:
        case GetVehiclePlateListForNoUsed:
        case GetDrivingLicenseByIdApp:
        case GetIdentityCardByIdApp:
        case GetDriversLicensedByIdApp:
        case ForceUpdatePassword:
        case PayReceivable:
        case PayPayable:
        case GetLastVersion:
            
            
            
            
        case Userinfo:
        {
            reqMthod = JYPost;
        }
            break;
            
        default:
            reqMthod = JYGet;
            break;
    }
    
    return reqMthod;
}


//检查网络
+ (BOOL)isConnectionAvailable{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        JYLog(@"Error. Could not recover network reachability flags");
        return NO;
    }
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}


@end
